<script setup>
import { getDictionaryByType, getDictionaryRoot, updateDictionaryValue, deleteDictionaryValue, addDictionaryValue, addDictionaryKey, deleteDictionaryKey } from '@/api/system'
import { onMounted, ref } from 'vue'

// 字典分级数组
const rootDictionaryList = ref([null, null, null])
// 选择的字典类型
const selectDictionaryType = ref({
  t: ['', '', '']
})
// 当前层的字典键id
const selectDictionaryFatherId = ref('0')
// 下层的字典键id
const selectDictionarySonId = ref('0')
// 选择框修改字典类型
const dictionaryTypeChange = async (value, typeLevel) => {
  // 寻找到当前dicType对应的id并绑定SonId
  for (let i = 0; i < rootDictionaryList.value[typeLevel].length; i++) {
    if (rootDictionaryList.value[typeLevel][i].dicType === value) {
      // 如果是根字典，那父字典id就是'0'，否则就是子字典
      selectDictionaryFatherId.value = !typeLevel ? '0' : selectDictionarySonId.value
      selectDictionarySonId.value = rootDictionaryList.value[typeLevel][i].id
      break
    }
  }
  switch (typeLevel) {
    case 0:
      // 移除一级字典
      rootDictionaryList.value[1] = null
      selectDictionaryType.value.t[1] = ''
    case 1:
      // 移除二级字典
      rootDictionaryList.value[2] = null
      selectDictionaryType.value.t[2] = ''
  }
  // 获取该类型的字典
  const tempRes = await getDictionaryByType(value)
  // 把字典映射到表格
  resMsgToTableData(tempRes[0].values)
  // 判断子节点是否为空
  if (tempRes[0].children.length === 0) {
    return
  }
  // 如果子节点不为空，可以根据传入的字典层级进行下一个层级的选择
  switch (typeLevel) {
    case 0:
      // 添加一级字典
      rootDictionaryList.value[1] = tempRes[0].children
      break
    case 1:
      // 添加二级字典
      rootDictionaryList.value[2] = tempRes[0].children
      break
  }
}
// 进行表单校验
const validateForm = async (formDom) => {
  let isPass = true
  await formDom.value.validate().then(res => {
    if (res) {
      isPass = false
    }
  })
  return isPass
}

// 用于展示的表格数据
const tableData = ref()
// 把获取的数据映射到表格中
const resMsgToTableData = (data) => {
  tableData.value = []
  data.forEach(item => {
    tableData.value.push({
      dicLabel: item.dicLabel,
      dicSort: item.dicSort,
      dicType: item.dicType,
      dicValue: item.dicValue,
      id: item.id
    })
  })
}

// 获取页面数据
const getPageData = async () => {
  // 如果获取过字典，就获取当前字典
  if (getDictionaryType()[0]) {
    const tempRes = await getDictionaryByType(getDictionaryType()[0])
    return tempRes[0].values
  }
  // 否则获取根字典
  return await getDictionaryRoot()
}

onMounted(async () => {
  // 获取根字典
  const tempRes = await getDictionaryRoot()
  rootDictionaryList.value[0] = tempRes
})

// 寻找当前最下层的字典类型
const getDictionaryType = () => {
  switch (true) {
    case selectDictionaryType.value.t[2] !== '':
      return [selectDictionaryType.value.t[2], 2]
    case selectDictionaryType.value.t[1] !== '':
      return [selectDictionaryType.value.t[1], 1]
    case selectDictionaryType.value.t[0] !== '':
      return [selectDictionaryType.value.t[0], 0]
    default:
      return [null, 0]
  }
}

// 新增字典值对话框可见度
const addDictionaryValueVisible = ref(false)
// 新增字典值对话框表单
const addDictionaryValueForm = ref({})
// 新增字典值对话框表单DOM元素
const addDictionaryValueFormDom = ref()
// 新增字典值对话框确认提交前
const addDictionaryValueBeforeOk = async () => {
  return validateForm(addDictionaryValueFormDom)
}
// 新增字典值对话框确认提交
const addDictionaryValueOk = async () => {
  addDictionaryValueForm.value.dicType = getDictionaryType()[0]
  await addDictionaryValue(addDictionaryValueForm.value)
  addDictionaryValueFormDom.value.resetFields()
  addDictionaryValueFormDom.value.clearValidate()
  resMsgToTableData(await getPageData())
}
// 新增字典值对话框取消提交
const addDictionaryValueCancel = () => {
  addDictionaryValueFormDom.value.resetFields()
  addDictionaryValueFormDom.value.clearValidate()
}

// 点击修改字典值按钮
const updateDictionaryValueModal = (record) => {
  record.dicSort = `${record.dicSort}`
  Object.assign(updateDictionaryValueForm.value, record)
  updateDictionaryValueVisible.value = true
}
// 修改字典值对话框可见度
const updateDictionaryValueVisible = ref(false)
// 修改字典值对话框表单
const updateDictionaryValueForm = ref({})
// 修改字典值对话框表单DOM元素
const updateDictionaryValueFormDom = ref()
// 修改字典值对话框确认提交前
const updateDictionaryValueBeforeOk = async () => {
  return validateForm(updateDictionaryValueFormDom)
}
// 修改字典值对话框确认提交
const updateDictionaryValueOk = async () => {
  await updateDictionaryValue(updateDictionaryValueForm.value)
  updateDictionaryValueFormDom.value.resetFields()
  updateDictionaryValueFormDom.value.clearValidate()
  resMsgToTableData(await getPageData())
}
// 修改字典值对话框取消提交
const updateDictionaryValueCancel = () => {
  updateDictionaryValueFormDom.value.resetFields()
  updateDictionaryValueFormDom.value.clearValidate()
}

// 点击删除字典值按钮
const deleteDictionaryValueModal = (record) => {
  deleteDictionaryValueVisible.value = true
  deleteDictionaryValueId.value = record.id
}
// 删除字典值对话框可见度
const deleteDictionaryValueVisible = ref(false)
// 删除字典值的id
const deleteDictionaryValueId = ref('')
// 删除字典值对话框确认提交
const deleteDictionaryValueOk = async () => {
  await deleteDictionaryValue(deleteDictionaryValueId.value)
  resMsgToTableData(await getPageData())
}












// 新增字典键的pid
const addDictionaryKeyPid = ref('')
// 新增字典键是下层还是本层（true本层，false下层）
const addDictionaryKeyLevel = ref(null)
// 点击新增字典键按钮
const addDictionaryKeyModel = (addType) => {
  // addType为true表示新增本级字典键，为false表示子级字典键
  addDictionaryKeyPid.value = addType ? selectDictionaryFatherId.value : selectDictionarySonId.value
  addDictionaryKeyLevel.value = addType
  addDictionaryKeyVisible.value = true
}
// 新增字典键对话框可见度
const addDictionaryKeyVisible = ref(false)
// 新增字典键对话框表单
const addDictionaryKeyForm = ref({})
// 新增字典键对话框表单DOM元素
const addDictionaryKeyFormDom = ref()
// 新增字典键对话框确认提交前
const addDictionaryKeyBeforeOk = async () => {
  return validateForm(addDictionaryKeyFormDom)
}
// 新增字典键对话框确认提交
const addDictionaryKeyOk = async () => {
  addDictionaryKeyForm.value.pid = addDictionaryKeyPid.value
  await addDictionaryKey(addDictionaryKeyForm.value)
  addDictionaryKeyFormDom.value.resetFields()
  addDictionaryKeyFormDom.value.clearValidate()
  // 如果是第0层的更改，则重新获取root，不是第0层就获取上一层的type
  // pid=0说明是第0层
  if (addDictionaryKeyPid.value === '0') {
    const tempRes = await getDictionaryRoot()
    rootDictionaryList.value[0] = tempRes
    selectDictionaryType.value.t0 = ''
  } else {
    // 不是第0层的更改，先找到这是哪层
    // 先判断是添加的下层还是本层
    if (addDictionaryKeyLevel.value) {
      // 添加的本层，就要找上一层的type
      const tempRes = await getDictionaryByType(selectDictionaryType.value.t[getDictionaryType()[1] - 1])
      rootDictionaryList.value[getDictionaryType()[1]] = tempRes[0].children
    } else {
      // 添加的下层，就找本层type
      const tempRes = await getDictionaryByType(selectDictionaryType.value.t[getDictionaryType()[1]])
      rootDictionaryList.value[getDictionaryType()[1] + 1] = tempRes[0].children
    }
  }
}
// 新增字典键对话框取消提交
const addDictionaryKeyCancel = () => {
  addDictionaryKeyFormDom.value.resetFields()
  addDictionaryKeyFormDom.value.clearValidate()
}

// 点击删除字典键按钮
const deleteDictionaryKeyModal = () => {
  deleteDictionaryKeyVisible.value = true
  deleteDictionaryKeyId.value = selectDictionarySonId.value
}
// 删除字典键对话框可见度
const deleteDictionaryKeyVisible = ref(false)
// 删除字典键的id
const deleteDictionaryKeyId = ref('')
// 删除字典键对话框确认提交
const deleteDictionaryKeyOk = async () => {
  await deleteDictionaryKey(deleteDictionaryKeyId.value)
  // 如果是第0层的更改，则重新获取root，不是第0层就获取上一层的type
  if (getDictionaryType()[1] === 0) {
    const tempRes = await getDictionaryRoot()
    rootDictionaryList.value[0] = tempRes
    selectDictionaryType.value.t[0] = ''
  } else {
    const tempRes = await getDictionaryByType(selectDictionaryType.value.t[getDictionaryType()[1] - 1])
    rootDictionaryList.value[getDictionaryType()[1]] = tempRes[0].children
    getDictionaryType()[1] - 1 === 0 ? selectDictionaryType.value.t[1] = '' : selectDictionaryType.value.t[2] = ''
  }
}
</script>

<template>
  <!-- 新增字典键对话框 start -->
  <a-modal v-model:visible="addDictionaryKeyVisible" @ok="addDictionaryKeyOk"
    :on-before-ok="addDictionaryKeyBeforeOk" @cancel="addDictionaryKeyCancel" title="新增字典键">
    <a-form :model="addDictionaryKeyForm" ref="addDictionaryKeyFormDom">
      <a-form-item field="dicName" label="字典名称" :rules="[{required:true,message:'字典名称不能为空'}]">
        <a-input v-model="addDictionaryKeyForm.dicName" placeholder="请输入字典名称" />
      </a-form-item>
      <a-form-item field="dicType" label="字典类型" :rules="[{required:true,message:'字典类型不能为空'}]">
        <a-input v-model="addDictionaryKeyForm.dicType" placeholder="请输入字典类型" />
      </a-form-item>
      <a-form-item field="dicSort" label="字典排序">
        <a-input v-model=" addDictionaryKeyForm.dicSort" placeholder="请输入字典排序" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 新增字典键对话框 end -->
  <!-- 删除字典键对话框 start -->
  <a-modal v-model:visible="deleteDictionaryKeyVisible" @ok="deleteDictionaryKeyOk" title="删除字典键">
    <div>你确定要删除该字典键吗</div>
  </a-modal>
  <!-- 删除字典键对话框 end -->
  <!-- 新增字典值对话框 start -->
  <a-modal v-model:visible="addDictionaryValueVisible" @ok="addDictionaryValueOk"
    :on-before-ok="addDictionaryValueBeforeOk" @cancel="addDictionaryValueCancel" title="新增字典值">
    <a-form :model="addDictionaryValueForm" ref="addDictionaryValueFormDom">
      <a-form-item field="dicLabel" label="字典标签" :rules="[{required:true,message:'字典标签不能为空'}]">
        <a-input v-model="addDictionaryValueForm.dicLabel" placeholder="请输入字典标签" />
      </a-form-item>
      <a-form-item field="dicValue" label="字典值" :rules="[{required:true,message:'字典值不能为空'}]">
        <a-input v-model="addDictionaryValueForm.dicValue" placeholder="请输入字典值" />
      </a-form-item>
      <a-form-item field="dicSort" label="字典排序">
        <a-input v-model="addDictionaryValueForm.dicSort" placeholder="请输入字典排序" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 新增字典值对话框 end -->
  <!-- 修改字典值对话框 start -->
  <a-modal v-model:visible="updateDictionaryValueVisible" @ok="updateDictionaryValueOk"
    :on-before-ok="updateDictionaryValueBeforeOk" @cancel="updateDictionaryValueCancel"
    title="修改字典值">
    <a-form :model="updateDictionaryValueForm" ref="updateDictionaryValueFormDom">
      <a-form-item field="dicLabel" label="字典标签" :rules="[{required:true,message:'字典标签不能为空'}]">
        <a-input v-model="updateDictionaryValueForm.dicLabel" placeholder="请输入字典标签" />
      </a-form-item>
      <a-form-item field="dicSort" label="字典排序" :rules="[{required:true,message:'字典排序不能为空'}]">
        <a-input v-model="updateDictionaryValueForm.dicSort" placeholder="请输入字典排序" />
      </a-form-item>
      <a-form-item field="dicValue" label="字典值" :rules="[{required:true,message:'字典值不能为空'}]">
        <a-input v-model="updateDictionaryValueForm.dicValue" placeholder="请输入字典值" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 修改字典值对话框 end -->
  <!-- 删除字典对话框 start -->
  <a-modal v-model:visible="deleteDictionaryValueVisible" @ok="deleteDictionaryValueOk"
    title="删除字典值">
    <div>你确定要删除该字典吗</div>
  </a-modal>
  <!-- 删除字典对话框 end -->
  <a-layout class="layout-demo">

    <a-layout-header>
      <!-- 查询参数输入区 start -->
      <div class="box">
        <span class="my-span">根字典</span>
        <a-select :style="{width:'140px'}" placeholder="选择根字典" v-model="selectDictionaryType.t[0]"
          @change="dictionaryTypeChange(selectDictionaryType.t[0], 0)">
          <a-option v-for="item in rootDictionaryList[0]" :key="item.dicType"
            :value="item.dicType">{{ item.dicName }}</a-option>
        </a-select>
      </div>
      <div class="box" v-if="rootDictionaryList[1]">
        <span class="my-span">一级字典</span>
        <a-select :style="{width:'140px'}" placeholder="选择一级字典" v-model="selectDictionaryType.t[1]"
          @change="dictionaryTypeChange(selectDictionaryType.t[1],1)">
          <a-option v-for="item in rootDictionaryList[1]" :key="item.dicType"
            :value="item.dicType">{{ item.dicName }}</a-option>
        </a-select>
      </div>
      <div class="box" v-if="rootDictionaryList[2]">
        <span class="my-span">二级字典</span>
        <a-select :style="{width:'140px'}" placeholder="选择二级字典" v-model="selectDictionaryType.t[2]"
          @change="dictionaryTypeChange(selectDictionaryType.t[2],2)">
          <a-option v-for="item in rootDictionaryList[2]" :key="item.dicType"
            :value="item.dicType">{{ item.dicName }}</a-option>
        </a-select>
      </div>
      <div class="box">
        <a-button class="my-btn" type="outline"
          @click="addDictionaryKeyModel(true)">新增字典键</a-button>
      </div>
      <div class="box">
        <a-button class="my-btn" type="outline" v-if="selectDictionaryType.t[0]"
          @click="addDictionaryKeyModel(false)">新增子字典键</a-button>
      </div>
      <div class="box">
        <a-button class="my-btn" type="outline" v-if="selectDictionaryType.t[0]"
          @click="deleteDictionaryKeyModal">删除字典键</a-button>
      </div>
      <div class="box">
        <!-- <a-button class="my-btn" type="outline"
          @click="addDictionaryVisible=!addDictionaryVisible">删除字典键</a-button> -->
      </div>
      <!-- 查询参数输入区 end -->
    </a-layout-header>
    <a-layout-content>
      <!-- 信息展示表格 start -->
      <a-table :data="tableData" class="my-table" :pagination="false" v-if="tableData">
        <template #columns>
          <a-table-column :align="'center'" title="排序" data-index="dicSort" :width="60" />
          <a-table-column :align="'center'" title="值" data-index="dicValue" />
          <a-table-column :align="'center'" title="标签" data-index="dicLabel" />
          <!-- 状态开关，0是停用，1是启用-->
          <a-table-column :align="'center'" title="操作" :width="180">
            <template #cell=record>
              <a-button type="outline" @click="updateDictionaryValueModal(record.record)"
                style="margin-right:20px">修改</a-button>
              <a-button type="outline"
                @click="deleteDictionaryValueModal(record.record)">删除</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <!-- 信息展示表格 end -->
      <div>
        <a-button class="table-end-addbtn" type="outline" v-if="getDictionaryType()[0]"
          @click="addDictionaryValueVisible=!addDictionaryValueVisible">新增字典值</a-button>
      </div>
    </a-layout-content>
    <a-layout-footer>Footer</a-layout-footer>
  </a-layout>
</template>

<style scoped>
.layout-demo :deep(.arco-layout-header) {
  height: auto;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  font-size: 16px;
  font-stretch: condensed;
  text-align: center;
}

.layout-demo :deep(.arco-layout-header) .box {
  display: inline-block;
  margin: 12px 0;
}

.my-btn {
  margin-left: 12px;
}

.layout-demo :deep(.arco-layout-sider) {
  width: 206px;
}

.table-head-div {
  margin-top: 40px;
}

.my-table {
  margin: 64px 64px 0;
}

.table-end-addbtn {
  margin: 12px 64px;
  float: right;
}

.my-span {
  margin: 0 12px;
}
</style>